package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewDownDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.heima.common.constants.WemediaConstants.WM_CONTENT_REFERENCE;



/**
 * @author げっしょく
 * @date 2021/11/22
 */
@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    /**
     * 查询文章
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findAll(WmNewsPageReqDto dto) {
        LambdaUpdateWrapper<WmNews> lam = new LambdaUpdateWrapper<>();
        if (dto.getStatus() != null) {
            lam.eq(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getBeginPubDate() != null) {
            lam.gt(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        if (dto.getEndPubDate() != null) {
            lam.lt(WmNews::getPublishTime, dto.getEndPubDate());
        }
        if (dto.getChannelId() != null) {
            lam.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (StringUtils.isNotEmpty(dto.getKeyword())) {
            lam.like(WmNews::getTitle,dto.getKeyword());
        }
        Integer page = dto.getPage();
        Integer size = dto.getSize();
        if (page == null) {
            page = 1;
        }
        if (size == null || size ==0) {
            size = 10;
        }
        IPage iPage = new Page(page, size);
        iPage = page(iPage, lam);
        List<WmNews> list = list(lam);
        PageResponseResult pageResponseResult = new PageResponseResult(page, size, (int)iPage.getTotal());
        pageResponseResult.setData(list);
        return pageResponseResult;
    }

    /**
     * 发布文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //判断dto中是否有图片
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            //使用工具类将集合中的图片url进行拼接使用逗号隔开
            String imageStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imageStr);
        }
        //如果是自动就将type的类型设置为null
        if (dto.getType() == -1) {
            wmNews.setType(null);
        }
        saveOrUpdateWmNews(wmNews);

        //保存的如果是草稿,就直接返回
        if (dto.getStatus() == WemediaConstants.CANCEL_COLLECT_MATERIAL) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        List<String> materials = ectractUrlInfo(dto.getContent());
        //设置图文和素材的关系, 如果没有图片则不保存
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            saveRelativeInfo(wmNews.getId(), materials, WM_CONTENT_REFERENCE);
            saveRelativeInfoForCover(dto,wmNews,materials);
        }


        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 判断封面的图片选择是否是自动
     * 1单图
     * 3是多图
     * 0是无图
     * @param dto
     * @param wmNews
     * @param materials
     */
    public void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {

        List<String> images = dto.getImages();
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            if (materials.size() > 1) {
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else if (materials.size() == 1) {
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else{
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            updateById(wmNews);
        }
        if (dto.getImages().size() > 0) {
            saveRelativeInfo(wmNews.getId(), images, WemediaConstants.WM_COVER_REFERENCE);
        }
    }



    @Autowired
    private WmMaterialService wmMaterialService;



    /**
     * 保存文章和图片素材的关系
     * @param id 文章id
     * @param materials 图片地址
     * @param type 类型
     */
    private void saveRelativeInfo(Integer id, List<String> materials, Short type) {
        LambdaUpdateWrapper<WmMaterial> lam = new LambdaUpdateWrapper<>();
        lam.in(WmMaterial::getUrl, materials);
        List<WmMaterial> list = wmMaterialService.list(lam);
        //如果从数据中读取的数据为空或者小于等于0就代表素材失效了,找不到
        if (list == null || list.size() <= 0) {
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }
        //从数据库中读取的数据少于url集合的长度也证明有素材失效了
        if (list.size() < materials.size()) {
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }
        //获取集合中所有素材的id
        List<Integer> materialIds = list.stream().map(item -> item.getId()).collect(Collectors.toList());

        wmNewsMaterialMapper.saveRelations(materialIds, id, type);
        /**
         * 方法二:  提取出一个个关系对象,然后创建WmNewsMaterial的service和实现类,
         *          继承MybatisPlus的类,然后调用savelist方法,记性批量保存
         * List<WmNewsMaterial> wmNewsMaterials = new ArrayList<>();
         * for (WmMaterial wmMaterial : list) {
         *      WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
         *      wmNewsMaterial.setNewsId(id);
         *      wmNewsMaterial.setMaterialId(wmMaterial.getId());
         *      wmNewsMaterial.setOrd((short) 0);
         *      wmNewsMaterial.setType(type);
         *      wmNewsMaterials.add(wmNewsMaterial);
         *     }
         *
         */


    }

    //获取图文内容中的图片信息
    private List<String> ectractUrlInfo(String content) {
        List<String> list = new ArrayList<>();
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        //map中键是type是image的就代表是图片
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                //通过键value就能获取到图片url地址
                String value = map.get("value").toString();
                list.add(value);
            }
        }
        return list;
    }

    /**
     * 保存文章的信息到wm_news表
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setUserId(WmThreadLocalUtil.getThread().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);  //默认是上架

        //判断id是否为空
        if (wmNews.getId() == null) {
            save(wmNews);
        } else {
            LambdaUpdateWrapper<WmNewsMaterial> lam = new LambdaUpdateWrapper<>();
            lam.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(lam);
            updateById(wmNews);
        }
    }

    /**
     * 删除文章
     * @param id 文章id
     * @return
     */
    @Override
    public ResponseResult deleteNew(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(501, "文章id不可缺少");
        }
        WmNews byId = getById(id);
        if (byId == null) {
            return ResponseResult.errorResult(1002, "文章不存在");
        }
        Short enable = byId.getEnable();
        if (enable == 1) {
            return ResponseResult.errorResult(501, "文章已发布, 不能删除");
        }
        removeById(id);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult getOneNew(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(501, "文章id不可缺少");
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(1002, "文章不存在");
        }

        return ResponseResult.okResult(wmNews);
    }

    /**
     * 文件上架和下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrAndUp(WmNewDownDto dto) {
        //判断参数是否为空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer id = dto.getId();
        Short enable = dto.getEnable();
        //判断用户文章id是否为空和小于等于0, 以及上下架参数是否合法
        if (id == null && id <=0 || enable == null && enable < 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //修改数据库数据
        LambdaUpdateWrapper<WmNews> lam = new LambdaUpdateWrapper<>();
        lam.eq(WmNews::getId, id).set(WmNews::getEnable, enable);
        boolean update = update(lam);
        if (update) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else{
            return ResponseResult.errorResult(501, "文章下架失败");
        }
    }


}
